package io.github.liuyuhao412.manager.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.github.liuyuhao412.manager.entity.User;
import io.github.liuyuhao412.manager.request.ApiResponse;
import io.github.liuyuhao412.manager.request.BaseRequest;
import io.github.liuyuhao412.manager.request.BaseResponse;
import io.github.liuyuhao412.manager.request.CreateUserRequest;
import io.github.liuyuhao412.manager.request.LoginRequest;
import io.github.liuyuhao412.manager.request.LoginResponse;
import io.github.liuyuhao412.manager.request.UpdateUserRequest;
import io.github.liuyuhao412.manager.service.TokenService;
import io.github.liuyuhao412.manager.service.UserService;

@RestController
@RequestMapping("/api")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private TokenService tokenService;

	@PostMapping("/login")
	public ApiResponse<LoginResponse> login(@RequestBody LoginRequest request) {
		User user = userService.login(request);
		String token = tokenService.generateToken(user.getId(), user.getUsername());
		return LoginResponse.success(user.getId(), user.getUsername(), token);
	}

	@GetMapping("/users")
	@PreAuthorize("hasRole('ADMIN')")
	public ApiResponse<List<User>> listUsers() {
		List<User> users = userService.listUsers();
		return ApiResponse.success(users);
	}

	@PostMapping("/users/create")
	@PreAuthorize("hasRole('ADMIN')")
	public ApiResponse<BaseResponse> createUser(@RequestBody CreateUserRequest request) {
		User user = userService.createUser(request);
		return BaseResponse.success(user.getId());
	}

	@PostMapping("/users/update")
	@PreAuthorize("hasRole('ADMIN')")
	public ApiResponse<BaseResponse> updateUser(@RequestBody UpdateUserRequest request) {
		User user = userService.updateUser(request);
		return BaseResponse.success(user.getId());
	}

	@PostMapping("/users/delete")
	@PreAuthorize("hasRole('ADMIN')")
	public ApiResponse<BaseResponse> deleteUser(@RequestBody BaseRequest request) {
		userService.deleteUser(request.getId());
		return BaseResponse.success(request.getId());
	}

}
